package team.paimengshop.show;

import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import team.paimengshop.server_database.OrderOperate;
import team.paimengshop.server_dataclass.Commodity;
import team.paimengshop.server_dataclass.Order;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class orderViewController implements Initializable
{
    private final TableView<MyOrder> table = new TableView<>();
    private final ObservableList<MyOrder> data =
            FXCollections.observableArrayList();

    @FXML
    private AnchorPane orderPane;

    @FXML
    private Button button1;

    @FXML
    private Button button2;

    @FXML
    private TextField textInput1;

    @FXML
    private TextField textInput2;

    private TableColumn idCol;

    private TableColumn paymentCol;

    private TableColumn userIdCol;

    private TableColumn addressCol;

    private TableColumn commodityNumberCol;

    private TableColumn commodityListCol;

    private ArrayList<Integer> idList;

    private ArrayList<Integer> userIdList;

    private ArrayList<Order> orderArrayList;

    @FXML
    private Button refreshButton;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle)
    {
        orderArrayList = OrderOperate.GetAllOrder();
        for(int i = 0; i < orderArrayList.size(); i++)
        {
            Order order = orderArrayList.get(i);
            MyOrder myOrder = new MyOrder(order.getId(), order.getPayment(), order.getUserId(), order.getAddress(), order.getCommodityNumber(),
                    Commodity.commodityArrayListToString(order.getCommodityList()));
            data.add(myOrder);
        }

        table.setEditable(true);

        idCol = new TableColumn("Id");
        idCol.setMinWidth(200);
        idCol.setCellValueFactory(
                new PropertyValueFactory<>("id"));

        paymentCol = new TableColumn("payment");
        paymentCol.setMinWidth(200);
        paymentCol.setCellValueFactory(
                new PropertyValueFactory<>("payment"));

        userIdCol = new TableColumn("userId");
        userIdCol.setMinWidth(200);
        userIdCol.setCellValueFactory(
                new PropertyValueFactory<>("userId"));

        addressCol = new TableColumn("address");
        addressCol.setMinWidth(200);
        addressCol.setCellValueFactory(
                new PropertyValueFactory<>("address"));

        commodityNumberCol = new TableColumn("commodityNumber");
        commodityNumberCol.setMinWidth(200);
        commodityNumberCol.setCellValueFactory(
                new PropertyValueFactory<>("commodityNumber"));

        commodityListCol = new TableColumn("commodityList");
        commodityListCol.setMinWidth(200);
        commodityListCol.setCellValueFactory(
                new PropertyValueFactory<>("commodityList"));

        table.setPrefWidth(1200);
        table.setPrefHeight(550);
        table.setItems(data);
        table.getColumns().addAll(idCol, paymentCol, userIdCol,addressCol,commodityNumberCol, commodityListCol);

        orderPane.getChildren().add(table);

        idList = new ArrayList<>();
        for(int i = 0; i < orderArrayList.size(); i++)
        {
            idList.add((Integer)idCol.getCellData(i));
        }
        userIdList = new ArrayList<>();
        for(int i = 0; i < orderArrayList.size(); i++)
        {
            userIdList.add((Integer) userIdCol.getCellData(i));
        }
    }

    public void Button1Clicked(ActionEvent actionEvent)
    {
        if(textInput1.getText().equals("") || textInput1.getText() == null)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询");
            alert.setContentText("订单id不能为空！");
            alert.setHeaderText("查询失败");
            alert.showAndWait();
        }
        else
        {
            idCol.setSortType(TableColumn.SortType.ASCENDING);
            table.requestFocus();
            int index;
            try
            {
                index = BinarySearch(idList, Integer.parseInt(textInput1.getText()));
            }
            catch (NumberFormatException e)
            {
                index = -1;
            }
            if(index != -1)
            {
                table.getSelectionModel().select(index);
                table.scrollTo(index);
                textInput1.clear();
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("查询");
                alert.setContentText("订单id不存在！");
                alert.setHeaderText("查询失败");
                alert.showAndWait();
                textInput1.clear();
            }
        }
    }

    public void Button2Clicked(ActionEvent actionEvent)
    {
        if(textInput2.getText().equals("") || textInput2.getText() == null)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询");
            alert.setContentText("userId不能为空！");
            alert.setHeaderText("查询失败");
            alert.showAndWait();
        }
        else
        {
            userIdCol.setSortType(TableColumn.SortType.ASCENDING);
            table.requestFocus();
            int index = BinarySearch(userIdList, Integer.parseInt(textInput2.getText()));
            if(index != -1)
            {
                table.getSelectionModel().select(index);
                table.scrollTo(index);
                textInput2.clear();
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("查询");
                alert.setContentText("userId不存在！");
                alert.setHeaderText("查询失败");
                alert.showAndWait();
                textInput2.clear();
            }
        }
    }

    public void Refresh(ActionEvent actionEvent)
    {
        data.clear();
        table.refresh();
        orderArrayList.clear();
        orderArrayList = OrderOperate.GetAllOrder();
        for(int i = 0; i < orderArrayList.size(); i++)
        {
            Order order = orderArrayList.get(i);
            MyOrder myOrder = new MyOrder(order.getId(), order.getPayment(), order.getUserId(), order.getAddress(), order.getCommodityNumber(),
                    Commodity.commodityArrayListToString(order.getCommodityList()));
            data.add(myOrder);
        }

        table.setEditable(true);

        idCol = new TableColumn("Id");
        idCol.setMinWidth(200);
        idCol.setCellValueFactory(
                new PropertyValueFactory<>("id"));

        paymentCol = new TableColumn("payment");
        paymentCol.setMinWidth(200);
        paymentCol.setCellValueFactory(
                new PropertyValueFactory<>("payment"));

        userIdCol = new TableColumn("userId");
        userIdCol.setMinWidth(200);
        userIdCol.setCellValueFactory(
                new PropertyValueFactory<>("userId"));

        addressCol = new TableColumn("address");
        addressCol.setMinWidth(200);
        addressCol.setCellValueFactory(
                new PropertyValueFactory<>("address"));

        commodityNumberCol = new TableColumn("commodityNumber");
        commodityNumberCol.setMinWidth(200);
        commodityNumberCol.setCellValueFactory(
                new PropertyValueFactory<>("commodityNumber"));

        commodityListCol = new TableColumn("commodityList");
        commodityListCol.setMinWidth(200);
        commodityListCol.setCellValueFactory(
                new PropertyValueFactory<>("commodityList"));

        table.setPrefWidth(1200);
        table.setPrefHeight(550);
        table.setItems(data);
        table.getColumns().addAll(idCol, paymentCol, userIdCol,addressCol,commodityNumberCol, commodityListCol);

        idList = new ArrayList<>();
        for(int i = 0; i < orderArrayList.size(); i++)
        {
            idList.add((Integer)idCol.getCellData(i));
        }
        userIdList = new ArrayList<>();
        for(int i = 0; i < orderArrayList.size(); i++)
        {
            userIdList.add((Integer) userIdCol.getCellData(i));
        }
    }


    public static class MyOrder   //订单数据模板，用于绑定表格中的单元
    {
        private final SimpleIntegerProperty id;
        private final SimpleDoubleProperty payment;
        private final SimpleIntegerProperty userId;
        private final SimpleStringProperty address;
        private final SimpleIntegerProperty commodityNumber;

        private final SimpleStringProperty commodityList;


        private MyOrder(int id, double payment, int userId, String address, int commodityNumber, String commodityList)
        {
            this.id = new SimpleIntegerProperty(id);
            this.payment = new SimpleDoubleProperty(payment);
            this.userId = new SimpleIntegerProperty(userId);
            this.address = new SimpleStringProperty(address);
            this.commodityNumber = new SimpleIntegerProperty(commodityNumber);
            this.commodityList = new SimpleStringProperty(commodityList);
        }

        public int getId() {
            return id.get();
        }

        public SimpleIntegerProperty idProperty() {
            return id;
        }

        public void setId(int id) {
            this.id.set(id);
        }

        public double getPayment() {
            return payment.get();
        }

        public SimpleDoubleProperty paymentProperty() {
            return payment;
        }

        public void setPayment(double payment) {
            this.payment.set(payment);
        }

        public int getUserId() {
            return userId.get();
        }

        public SimpleIntegerProperty userIdProperty() {
            return userId;
        }

        public void setUserId(int userId) {
            this.userId.set(userId);
        }

        public String getAddress() {
            return address.get();
        }

        public SimpleStringProperty addressProperty() {
            return address;
        }

        public void setAddress(String address) {
            this.address.set(address);
        }

        public int getCommodityNumber() {
            return commodityNumber.get();
        }

        public SimpleIntegerProperty commodityNumberProperty() {
            return commodityNumber;
        }

        public void setCommodityNumber(int commodityNumber) {
            this.commodityNumber.set(commodityNumber);
        }

        public String getCommodityList()
        {
            return commodityList.get();
        }

        public SimpleStringProperty commodityListProperty()
        {
            return commodityList;
        }

        public void setCommodityList(String commodityList)
        {
            this.commodityList.set(commodityList);
        }
    }

    public static int BinarySearch(ArrayList<Integer> idList, int id)
    {
        int begin = 0;
        int end = idList.size() - 1;
        while(begin <= end)
        {
            int mid = (begin + end) / 2;
            if(idList.get(mid) > id)
            {
                end = mid - 1;
            }
            else if(idList.get(mid) < id)
            {
                begin = mid + 1;
            }
            else
            {
                return mid;
            }
        }
        return -1;
    }
}
